import json
import os
from typing import Dict, Any, List

class ConfigManager:
    """配置管理器，负责处理API密钥和设置的保存与加载"""
    
    def __init__(self, config_file: str = "config.json"):
        self.config_file = config_file
        self.config = self._load_config()
        self.config_dir = os.path.dirname(os.path.abspath(__file__)).replace('utils', 'config')
        self.models_config_file = os.path.join(self.config_dir, "models.json")
        self.roles_config_file = os.path.join(self.config_dir, "roles.json")
        self._ensure_default_roles()
    
    def _load_models_config(self) -> Dict[str, Any]:
        """从models.json加载模型配置"""
        if os.path.exists(self.models_config_file):
            try:
                with open(self.models_config_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
            except json.JSONDecodeError:
                return {"models": {}, "current_model": "", "current_role": "助手"}
        return {"models": {}, "current_model": "", "current_role": "助手"}
    
    def _load_roles_config(self) -> Dict[str, Any]:
        """从roles.json加载角色配置"""
        if os.path.exists(self.roles_config_file):
            try:
                with open(self.roles_config_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
            except json.JSONDecodeError:
                return {}
        return {}
    
    def _save_models_config(self, config: Dict[str, Any]) -> None:
        """保存模型配置到models.json"""
        with open(self.models_config_file, 'w', encoding='utf-8') as f:
            json.dump(config, f, indent=4, ensure_ascii=False)
    
    def _save_roles_config(self, config: Dict[str, Any]) -> None:
        """保存角色配置到roles.json"""
        with open(self.roles_config_file, 'w', encoding='utf-8') as f:
            json.dump(config, f, indent=4, ensure_ascii=False)
    
    def get_models_from_config(self) -> Dict[str, Dict[str, Any]]:
        """从models.json获取模型配置"""
        models_config = self._load_models_config()
        return models_config.get("models", {})
    
    def get_model_names(self) -> List[str]:
        """获取所有模型名称列表"""
        models = self.get_models_from_config()
        return list(models.keys())
    
    def get_model_names_from_config(self) -> List[str]:
        """获取所有模型名称列表（别名方法）"""
        return self.get_model_names()
    
    def get_current_model_from_config(self) -> str:
        """从models.json获取当前选中的模型"""
        models_config = self._load_models_config()
        return models_config.get("current_model", "")
    
    def save_current_model_to_config(self, model_name: str) -> None:
        """保存当前选中的模型到models.json"""
        models_config = self._load_models_config()
        models_config["current_model"] = model_name
        self._save_models_config(models_config)
    
    def get_roles_from_config(self) -> Dict[str, Dict[str, str]]:
        """从roles.json获取角色配置"""
        return self._load_roles_config()
    
    def get_role_names_from_config(self) -> List[str]:
        """从roles.json获取所有角色名称列表"""
        roles = self.get_roles_from_config()
        return list(roles.keys())
    
    def get_current_role_from_config(self) -> str:
        """从models.json获取当前选中的角色"""
        models_config = self._load_models_config()
        return models_config.get("current_role", "助手")
    
    def save_current_role_to_config(self, role_name: str) -> None:
        """保存当前选中的角色到models.json"""
        models_config = self._load_models_config()
        models_config["current_role"] = role_name
        self._save_models_config(models_config)

    def _load_config(self) -> Dict[str, Any]:
        """加载配置文件"""
        if os.path.exists(self.config_file):
            try:
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
            except json.JSONDecodeError:
                return {}
        return {}
    
    def _ensure_default_roles(self):
        """确保默认角色配置存在"""
        if 'roles' not in self.config:
            self.config['roles'] = {
                "助手": {
                    "name": "助手",
                    "system_prompt": "你是一个友善的AI助手，请用中文回答问题。"
                },
                "老师": {
                    "name": "老师", 
                    "system_prompt": "你是一个耐心的老师，善于解释复杂概念，请用通俗易懂的方式回答问题。"
                },
                "程序员": {
                    "name": "程序员",
                    "system_prompt": "你是一个经验丰富的程序员，擅长各种编程语言和技术，能够提供准确的代码建议和给出该问题的答案。"
                },
                "翻译": {
                    "name": "翻译",
                    "system_prompt": "你是一个专业的翻译，能够准确地在中文和其他语言之间进行翻译，保持原文的意思和语调。"
                },
                "写作助手": {
                    "name": "写作助手",
                    "system_prompt": "你是一个专业的写作助手，能够帮助用户改进文章结构、语法和表达，提供创意和建议。"
                }
            }
            self.save_config(self.config)
    
    def save_config(self, config: Dict[str, Any]) -> None:
        """保存配置到文件"""
        with open(self.config_file, 'w', encoding='utf-8') as f:
            json.dump(config, f, indent=4, ensure_ascii=False)
        self.config = config
    
    def get_api_key(self, model_name: str) -> str:
        """获取指定模型的API密钥"""
        return self.config.get('api_keys', {}).get(model_name, '')
    
    def save_api_key(self, model_name: str, api_key: str) -> None:
        """保存指定模型的API密钥"""
        if 'api_keys' not in self.config:
            self.config['api_keys'] = {}
        self.config['api_keys'][model_name] = api_key
        self.save_config(self.config)
    
    def get_typing_speed(self) -> int:
        """获取打字速度设置"""
        return self.config.get('typing_speed', 30)
    
    def save_typing_speed(self, speed: int) -> None:
        """保存打字速度设置"""
        self.config['typing_speed'] = speed
        self.save_config(self.config)
    
    def get_setting(self, key: str, default: Any = None) -> Any:
        """获取通用设置"""
        return self.config.get(key, default)
    
    def save_setting(self, key: str, value: Any) -> None:
        """保存通用设置"""
        self.config[key] = value
        self.save_config(self.config)
    
    def get_roles(self) -> Dict[str, Dict[str, str]]:
        """获取所有角色配置"""
        return self.config.get('roles', {})
    
    def get_role_names(self) -> List[str]:
        """获取所有角色名称列表"""
        return list(self.get_roles().keys())
    
    def get_role_config(self, role_name: str) -> Dict[str, str]:
        """获取指定角色的配置"""
        # 优先从roles.json获取角色配置
        roles_from_file = self.get_roles_from_config()
        if role_name in roles_from_file:
            return roles_from_file[role_name]
        
        # 如果roles.json中没有，则从config.json获取
        roles = self.get_roles()
        return roles.get(role_name, {
            "name": role_name,
            "system_prompt": "你是一个友善的AI助手，请用中文回答问题。"
        })
    
    def save_role_config(self, role_name: str, system_prompt: str) -> None:
        """保存角色配置"""
        if 'roles' not in self.config:
            self.config['roles'] = {}
        
        self.config['roles'][role_name] = {
            "name": role_name,
            "system_prompt": system_prompt
        }
        self.save_config(self.config)
    
    def delete_role_config(self, role_name: str) -> bool:
        """删除角色配置"""
        if 'roles' in self.config and role_name in self.config['roles']:
            # 不允许删除默认角色
            if role_name == "助手":
                return False
            del self.config['roles'][role_name]
            self.save_config(self.config)
            return True
        return False
    
    def get_model_configs(self) -> Dict[str, Dict[str, Any]]:
        """获取模型配置"""
        return self.config.get('model_configs', {})
    
    def save_model_config(self, model_name: str, config: Dict[str, Any]) -> None:
        """保存模型配置"""
        if 'model_configs' not in self.config:
            self.config['model_configs'] = {}
        
        self.config['model_configs'][model_name] = config
        self.save_config(self.config)
    
    def get_current_model(self) -> str:
        """获取当前选中的模型"""
        return self.config.get('current_model', '')
    
    def save_current_model(self, model_name: str) -> None:
        """保存当前选中的模型"""
        self.config['current_model'] = model_name
        self.save_config(self.config)
    
    def get_current_role(self) -> str:
        """获取当前选中的角色"""
        return self.config.get('current_role', '助手')
    
    def save_current_role(self, role_name: str) -> None:
        """保存当前选中的角色"""
        self.config['current_role'] = role_name
        self.save_config(self.config)